package com.summer.framework.common.config.feign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.summer.framework.common.entity.FeignError;
import com.summer.framework.common.exception.BaseException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @auther: 杨杰
 * @date: 2019/5/16 14:10
 * @description:
 */
@Slf4j
public class NotBreakerConfiguration {

    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }

    /**
     * 自定义错误解码器
     */
    public class UserErrorDecoder implements ErrorDecoder {
        @Override
        public Exception decode(String methodKey, Response response) {
            Exception exception = null;
            try {
                // 获取原始的返回内容
                String json = Util.toString(response.body().asReader());
                log.info("decode  json:" + json);
                JSONObject userJson = JSONObject.parseObject(json);
                FeignError result = JSON.toJavaObject(userJson, FeignError.class);
                exception = new BaseException(result.getStatus(), result.getMessage());
                /*if (400 <= response.status() && response.status() < 500){
                    exception = new HystrixBadRequestException("request exception wrapper", exception);
                }else{
                    log.error(exception.getMessage(), exception);
                }*/
            } catch (IOException ex) {
                log.error(ex.getMessage(), ex);
            }
            return exception;
        }
    }
}
